<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left" />
      <el-button
        v-if="crud.optShow.add"
        v-permission="permission.add"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="crud.toAdd"
      >
        新增
      </el-button>
      <el-button
        v-if="crud.optShow.edit"
        v-permission="permission.edit"
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-edit"
        :disabled="crud.selections.length !== 1"
        @click="crud.toEdit(crud.selections[0])"
      >
        修改
      </el-button>
      <el-button
        v-if="crud.optShow.del"
        slot="reference"
        v-permission="permission.del"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        :loading="crud.delAllLoading"
        :disabled="crud.selections.length === 0"
        @click="toDelete(crud.selections)"
      >
        删除
      </el-button>
      <el-button
        v-if="crud.optShow.download"
        :loading="crud.downloadLoading"
        :disabled="!crud.data.length"
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-download"
        @click="crud.doExport"
      >导出</el-button>

      <el-button
        v-if="crud.optShow.import"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-upload2"
        @click="crud.toImport"
      >导入</el-button>
      <!--右侧-->
      <slot name="right" />
    </span>
    <el-button-group class="crud-opts-right">
      <el-button
        size="mini"
        plain
        type="info"
        icon="el-icon-search"
        @click="toggleSearch()"
      />
      <el-button
        size="mini"
        icon="el-icon-refresh"
        @click="crud.refresh()"
      />
      <el-popover
        placement="bottom-end"
        width="150"
        trigger="click"
      >
        <el-button
          slot="reference"
          size="mini"
          icon="el-icon-s-grid"
        >
          <i
            class="fa fa-caret-down"
            aria-hidden="true"
          />
        </el-button>
        <el-checkbox
          v-model="allColumnsSelected"
          :indeterminate="allColumnsSelectedIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox
          v-for="item in tableColumns"
          :key="item.property"
          v-model="item.visible"
          @change="handleCheckedTableColumnsChange(item)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-popover>
    </el-button-group>

    <el-dialog :title="crud.status.title"  :before-close="crud.closeImport" :visible.sync="crud.status.import > 0">
      <el-row :gutter="20" >
        <el-col :span="24">
          <el-collapse v-model="activeNames">
            <el-collapse-item v-if="crud.importConfig.templateUrl" title="下载模板" name="0">
              <div style="width: 100%;text-align: center">
                <el-button @click="crud.downloadTemplate" icon="el-icon-download" style="width: 80%" type="primary" plain>点击下载导入模板</el-button>
              </div>
            </el-collapse-item>
            <el-collapse-item title="Excel上传" name="2">
              <div style="width: 100%;text-align: center">
                <UploadExcel :onSuccess="onSuccess"></UploadExcel>
              </div>
            </el-collapse-item>
            <el-collapse-item title="配置字段关系" name="1" v-if="inputColumns.length != 0">
              <div class="warning">
                <p>请核对下面<strong> Excel表头字段 </strong>和表格字段无误后再上传，如果有差异修改正确后再上传。</p>
              </div>
              <template>
                <el-table
                  border
                  size="mini"
                  :data="inputColumns"
                  style="width: 100%">
                  <el-table-column
                    prop="property"
                    label="字段"
                    align="center">
                  </el-table-column>
                  <el-table-column
                    prop="label"
                    label="名称"
                    align="center">
                  </el-table-column>
                  <el-table-column
                    prop="excel"
                    label="Excel字段"
                    align="center">
                    <template scope="scope">
                      <el-input v-model="scope.row.excel" v-show="scope.row.seen"
                                @blur="loseFcous(scope.$index, scope.row)" > </el-input>
                      <span style="margin-left: 10px" v-show="!scope.row.seen" >
                            {{ scope.row.excel }}
                            <el-link type="primary" style="float: right; padding: 3px 0"><i class="el-icon-edit" @click="cellClick(scope.row)"></i></el-link>
                          </span>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, { crud } from '@crud/crud'
import UploadExcel from '@/components/UploadExcel'

function sortWithRef(src, ref) {
  const result = Object.assign([], ref)
  let cursor = -1
  src.forEach(e => {
    const idx = result.indexOf(e)
    if (idx === -1) {
      cursor += 1
      result.splice(cursor, 0, e)
    } else {
      cursor = idx
    }
  })
  return result
}

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export default {
  name: 'CRUD.operation',
  mixins: [crud()],
  components:{ UploadExcel },
  props: {
    permission: {
      type: Object,
      default: () => { return {} }
    },
    hiddenColumns: {
      type: Array,
      default: () => { return [] }
    },
    ignoreColumns: {
      type: Array,
      default: () => { return [] }
    },
    judge: Boolean
  },
  data() {
    return {
      activeNames: ['0','1','2'],
      tableColumns: [],
      inputColumns: [],
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      tableUnwatcher: null,
      // 忽略下次表格列变动
      ignoreNextTableColumnsChange: false
    }
  },
  watch: {
    'crud.props.table'() {
      this.updateTableColumns()
      this.tableColumns.forEach(column => {
        if (this.hiddenColumns.indexOf(column.property) !== -1) {
          column.visible = false
          this.updateColumnVisible(column)
        }
      })
    },
    'crud.props.table.store.states.columns'() {
      this.updateTableColumns()
    }
  },
  created() {
    this.crud.updateProp('searchToggle', true)
  },
  methods: {
    loseFcous(index, row) {
      row.seen = false;
    },
    cellClick(row, column) {
      row.seen = true;
    },
    updateTableColumns() {
      const table = this.crud.getTable()
      if (!table) {
        this.tableColumns = []
        return
      }
      let cols = null
      const columnFilter = e => e && e.type === 'default' && e.property && this.ignoreColumns.indexOf(e.property) === -1
      const refCols = table.columns.filter(columnFilter)
      if (this.ignoreNextTableColumnsChange) {
        this.ignoreNextTableColumnsChange = false
        return
      }
      this.ignoreNextTableColumnsChange = false
      const columns = []
      const inputColumns = []
      const fullTableColumns = table.$children.map(e => e.columnConfig).filter(columnFilter)
      cols = sortWithRef(fullTableColumns, refCols)
      cols.forEach(config => {
        const column = {
          property: config.property,
          label: config.label,
          visible: refCols.indexOf(config) !== -1
        }
        const inputColumn = {
          property: config.property,
          label: config.label,
          excel: config.label,
          seen: false
        }
        columns.push(column)
        inputColumns.push(inputColumn)
      })
      this.tableColumns = columns
      this.inputColumns = inputColumns
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      this.tableColumns.forEach(column => {
        if (!column.visible) {
          column.visible = true
          this.updateColumnVisible(column)
        }
      })
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      this.tableColumns.forEach(column => {
        ++totalCount
        selectedCount += column.visible ? 1 : 0
      })
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
      this.updateColumnVisible(item)
    },
    updateColumnVisible(item) {
      const table = this.crud.props.table
      const vm = table.$children.find(e => e.prop === item.property)
      const columnConfig = vm.columnConfig
      if (item.visible) {
        // 找出合适的插入点
        const columnIndex = this.tableColumns.indexOf(item)
        vm.owner.store.commit('insertColumn', columnConfig, columnIndex + 1, null)
      } else {
        vm.owner.store.commit('removeColumn', columnConfig, null)
      }
      this.ignoreNextTableColumnsChange = true
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    },
    //导入成功得到数据
    onSuccess(data){
      if(!data.results || !data.header){
        this.$notify.error({
          title: '错误',
          message: '解析Excel失败！Excel数据空！'
        });
        return false;
      }
      //如果配置里配置了回调函数则直接回调
      if(this.crud.importConfig.onSuccess &&  typeof this.crud.importConfig.onSuccess === "function"){
        if(this.crud.importConfig.onSuccess(data)){
          //关闭窗口
          this.crud.status.import = CRUD.STATUS.NORMAL;
        };
        return true;
      }

      if(this.inputColumns.length == 0){
        this.$notify.error({
          title: '错误',
          message: '组装数据失败：获取Table字段失败！'
        });
        return false;
      }
      //组装数据
      const excelDatas = []
      data.results.forEach(d =>{
        const excelData = {};
        this.inputColumns.forEach(e =>{
          var value = "";
          if(e.excel){
            value = d[e.excel];
            if(value instanceof Date){
              value = value.Format("yyyy-MM-dd HH:mm:ss");
            }
          }
          excelData[e.property] = value;
        })
        excelDatas.push(excelData);
      })
      this.crud.doImport(excelDatas);
      return true;
    }
  }

}
</script>

<style>
  .crud-opts {
    padding: 4px 0;
    display: -webkit-flex;
    display: flex;
    align-items: center;
  }
  .crud-opts .crud-opts-right {
    margin-left: auto;
  }
  .crud-opts .crud-opts-right span {
    float: left;
  }
  .warning {
    padding: 8px 16px;
    background-color: #fff6f7;
    border-radius: 4px;
    border-left: 5px solid #fe6c6f;
    margin: 20px 0;
  }
  .warning p {
    font-size: 14px;
    color: #fe6c6f;
    line-height: 1.5em;
  }
</style>
